//
//  DBDeviceIDFA.swift
//  DBCA
//
//  Created by mugua on 2024/7/3.
//

import Foundation
import AdSupport
import AppTrackingTransparency
import KeychainAccess

class DBDeviceIDFA {
    
    static func idfaByDevice() -> String {
        var idfa = ""
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    let idfaStr = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                    idfa = idfaStr
                case .denied, .restricted, .notDetermined:
                    DBLog("Tracking authorization denied or not determined.")
                @unknown default:
                    DBLog("Unknown tracking authorization status.")
                }
            }
        } else {
            idfa = self.getIDFA()
        }
        
        return idfa
    }
    
    private static func getIDFA() -> String {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            return ASIdentifierManager.shared().advertisingIdentifier.uuidString
        }
        return ""
    }
    
    static func getIDFV() -> String {
        let deviceIdentifier = UIDevice.current.identifierForVendor?.uuidString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        let saveContent = retrieveIDFVFromKeychain()
        if let saveContent = saveContent, saveContent.count > 0 {
            return saveContent
        } else {
            if let deviceIdentifier = deviceIdentifier, deviceIdentifier.count > 0 {
                storeIDFVToKeychain(idfv: deviceIdentifier)
            }
            
            return deviceIdentifier ?? ""
        }
    }
    
    private static func storeIDFVToKeychain(idfv: String) {
        let keychain = Keychain(service: "DeviceIdentifierByKeychain")
        keychain["IDFV"] = idfv
    }
    
    private static func retrieveIDFVFromKeychain() -> String? {
        let keychain = Keychain(service: "DeviceIdentifierByKeychain")
        return keychain["IDFV"]
    }
}

